<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Ext\Wechat\QRCode;

class QRCodeController extends Controller
{

    public function scene(Request $request)
    {
        $sceneID = $request->input('scene_id');
        if ($sceneID) {
            $expire = 7* 24 * 3600; // 7天有效期
            $root = './';
            $path = 'file/wechat/qr_code/';
            $fileName = $sceneID . '.jpg';
            # 如果文件存在并且没有过期可以使用缓存图片，减少请求量
            if (is_file($root . $path . $fileName)) {
                $time = filemtime($root . $path . $fileName) + $expire - 3600;
                if ($time > time()) {
                    return url($path . $fileName);
                }
            }
            # 如果文件目录不存在，创建一个文件目录
            if (!is_dir($root . $path)) @mkdir($root . $path, 0777, true);
            # 请求接口获取二维码
            $ticket = QRCode::ticket([
                'expire_seconds' => $expire,
                'scene_id' => $sceneID,
                'token' => $request->wechat->token,
                'action_name' => 'QR_SCENE'
            ]);
            $code = QRCode::code($ticket->ticket);
            # 保存二维码文件
            file_put_contents($root . $path . $fileName, $code);
            return url($path . $fileName);
        }
    }
}
